package org.linlinjava.litemall.wx.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.config.AlipayProperties;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallDisputeOrder;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.service.LitemallDisputeService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.DisputeConstant;
import org.linlinjava.litemall.db.util.OrderConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 阿里支付.已经沙箱验证
 */
@Service
public class AlipayService {
	private final Log logger = LogFactory.getLog(AlipayService.class);

	@Resource
	private AlipayClient alipayClient;

	@Resource
	private AlipayProperties alipayProperties;

	@Autowired
	private LitemallDisputeService disputeService;

	@Autowired
	private LitemallOrderService orderService;

	@Transactional(rollbackFor = Exception.class)
	public String nativePay(Integer userId, String body, HttpServletRequest request) {

		Integer orderId = JacksonUtil.parseInteger(body, "orderId");
/*		if (orderId == null) {
			return ResponseUtil.badArgument();
		}

		if (order == null) {
			return ResponseUtil.badArgumentValue();
		}
		if (!order.getUserId().equals(userId)) {
			return ResponseUtil.badArgumentValue();
		}*/
		LitemallOrder order = orderService.findById(orderId);

		String productCode = "FAST_INSTANT_TRADE_PAY";
		AlipayTradePagePayModel model = new AlipayTradePagePayModel();
		model.setOutTradeNo(order.getOrderSn());
		model.setSubject("NATIVE");
		model.setTotalAmount(order.getActualPrice().toString());
		model.setBody("订单：" + order.getOrderSn());
		model.setProductCode(productCode);

		AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
		//pagePayRequest.setReturnUrl(alipayProperties.getReturnUrl());
		pagePayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
		pagePayRequest.setBizModel(model);

		// 调用SDK生成表单, 并直接将完整的表单html输出到页面
		String retStr = null;
		try {
			retStr = alipayClient.pageExecute(pagePayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return retStr;
	}

	@Transactional
	public Object nativePayMargin(String body, HttpServletRequest request) {

		Integer disputeId = JacksonUtil.parseInteger(body, "disputeId");
		LitemallDisputeOrder disputeOrder = disputeService.findOrderById(disputeId);
		String tradeNo = disputeOrder.getDisputeSn();
		BigDecimal actualPrice = disputeOrder.getPayAmount();


		String productCode = "FAST_INSTANT_TRADE_PAY";
		AlipayTradePagePayModel model = new AlipayTradePagePayModel();
//		model.setOutTradeNo(UUID.randomUUID().toString());
		model.setOutTradeNo("margin_" + tradeNo);
		model.setSubject("NATIVE");
		model.setTotalAmount(actualPrice.toString());
		model.setBody("订单：" + "Margin" + "_" + tradeNo);
		model.setProductCode(productCode);

		AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
		pagePayRequest.setReturnUrl(alipayProperties.getReturnUrl());
		pagePayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
		pagePayRequest.setBizModel(model);

		// 调用SDK生成表单, 并直接将完整的表单html输出到页面
		String retStr = null;
		try {
			retStr = alipayClient.pageExecute(pagePayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return ResponseUtil.ok(retStr);
	}


	public String getwayPay() {
		String productCode = "FAST_INSTANT_TRADE_PAY";
		AlipayTradePagePayModel model = new AlipayTradePagePayModel();
		model.setOutTradeNo(UUID.randomUUID().toString());
		model.setSubject("游艇");
		model.setTotalAmount("1000000");
		model.setBody("豪华游艇");
		model.setProductCode(productCode);

		AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
		pagePayRequest.setReturnUrl(alipayProperties.getReturnUrl());
		pagePayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
		pagePayRequest.setBizModel(model);

		// 调用SDK生成表单, 并直接将完整的表单html输出到页面
		String retStr = null;
		try {
			retStr = alipayClient.pageExecute(pagePayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return retStr;
	}


	@Transactional
	public String payNotify(HttpServletRequest request, HttpServletResponse response) {


		Map<String, String[]> parameters = request.getParameterMap();
		Map<String, String> parameterMap = new HashMap<>();
		for (Object v : parameters.entrySet()) {
			Map.Entry<String, String[]> item = (Map.Entry<String, String[]>) v;
			parameterMap.put(item.getKey(), item.getValue()[0]);
		}
		String signType = parameterMap.get("sign_type");
		String trade_no = parameterMap.get("trade_no");
		String out_trade_no = parameterMap.get("out_trade_no");

		String alipayPublicKey = alipayProperties.getAlipayPublicKey();

		logger.info("处理支付宝的订单支付");
		//logger.info(parameterMap);
		try {
			if (AlipaySignature.rsaCheckV1(parameterMap, alipayPublicKey, "UTF-8", signType)) {
				String orderSn = out_trade_no;
				String payId = trade_no;

				if (orderSn.contains("margin")) {
					//保证金
					// 分转化成(圆角分)的圆
					String totalFee = parameterMap.get("total_amount");
					String sn = orderSn.split("_")[1];
					LitemallDisputeOrder order = disputeService.findOrderBySn(sn);
					if (order == null) {
						return "failure";
					}

					// 检查这个订单是否已经处理过
					if (order.getState().shortValue() == DisputeConstant.RECHECKING) {
						return "success";
					}

					// 检查支付订单金额
					if (!totalFee.equals(order.getPayAmount().toString())) {
						return "failure";
					}
					order.setPayId(payId);
					order.setPayTime(LocalDateTime.now());
					order.setState(DisputeConstant.RECHECKING);
					disputeService.updateWithOptimisticLocker(order);
					return "success";

				} else {
					//商品订单

					// 分转化成元
					String totalFee = parameterMap.get("total_amount");
					LitemallOrder order = orderService.findBySn(orderSn);
					if (order == null) {
						return "failure";
					}

					// 检查这个订单是否已经处理过
					if (order.getOrderStatus().shortValue() == OrderConstant.PAYED) {
						return "success";
					}

					// 检查支付订单金额
					if (!totalFee.equals(order.getActualPrice().toString())) {
						return "failure";
					}

					order.setPayId(payId);
					order.setPayTime(LocalDateTime.now());
					order.setOrderStatus(OrderConstant.PAYED);
					order.setPromiseTime(LocalDateTime.now().plusDays(order.getPromiseDate()));
					orderService.updateWithOptimisticLocker(order);
					return "success";
				}
			} else {
				return "failure";
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return "failure";
		}
	}
}

